'use strict';
const path = require('path');
const Package = require("@hl-imooc-cli-dev/package");
const log = require("@hl-imooc-cli-dev/log")
const cp = require('child_process');
const SETTINGS = {
    // init: "@hl-imooc-cli-dev/init"
    init: "@imooc-cli/init"
}
const CACHE_DIR = 'dependencies'

async function exec() {
    // TODO
    let pkg = '';
    let targetPath = process.env.CLI_TARGET_PATH;
    let storeDir = ''
    const homePath = process.env.CLI_HOME_PATH;
    log.verbose('targetPath', targetPath)
    log.verbose('homePath', homePath)

    const cmdObj = arguments[arguments.length - 1];
    const cmdName = cmdObj.name();
    const packageName = SETTINGS[cmdName];
    const packageVersion = 'latest';
    if (!targetPath) {
        targetPath = path.resolve(homePath, CACHE_DIR)  // 生成缓存路径
        storeDir = path.resolve(targetPath, 'node_modules')  // 生成缓存路径
        log.verbose('targetPath', targetPath)
        log.verbose('storeDir', storeDir)
        // 初始化 Package 对象
        pkg = new Package({
            targetPath,
            storeDir,
            packageName,
            packageVersion,
        })
        if (await pkg.exists()) {
            // 更新 package
            pkg.update()
            console.log('更新package')

        } else {
            // 安装 package
            await pkg.install();
        }
    } else {
        pkg = new Package({
            targetPath,
            packageName,
            packageVersion,
        })
    }
    const rootfile = pkg.getRootFilePath()
    if (rootfile) {
        // 在当前进程中调用
        // 在node子进程中调用
        try {
            // require(rootfile).call(null, Array.from(arguments))
            const args = Array.from(arguments)
            const cmd = args[args.length-1]
            const o = Object.create(null);
            Object.keys(cmd).forEach((key) => {
                if(cmd.hasOwnProperty(key) && 
                !key.startsWith('_') && 
                !key.startsWith('parent')
                ){
                    o[key] = cmd[key]
                }
            })
            args[args.length-1] = o;
            const code = `require('${rootfile}').call(null, ${JSON.stringify(args)})`
            const child = spawn('node',['-e', code], {
                cwd: process.cwd(),
                stdio:"inherit"  // 子进程的信息保留到父进程去打印
            }) 
            child.on('error', e => {
                log.error(e.message);
            })
            child.on('exit', e => {
                log.verbose('命令执行成功:',e);
            })
        } catch(e) {
            log.error(e.message)
        }
    }
}


function spawn(command,args,options){
    const win32 = process.platform === 'win32'
    const cmd = win32 ? 'cmd' : command
    const cmdArgs = win32 ? ['/c'].concat(command, args) :args
    return cp.spawn(cmd, cmdArgs, options || options)
}
module.exports = exec;